<template>
  <div class="grid grid-cols-1 md:grid-cols-2 min-h-screen">
    
    <!-- ==================== 左侧信息展示区 ==================== -->
    <div class="bg-slate-50 p-8 md:p-12 lg:p-16 flex flex-col">
      <!-- Slogan -->
      <header>
        <h1 class="text-4xl lg:text-5xl font-bold leading-tight bg-gradient-to-r from-primary to-violet-500 bg-clip-text text-transparent">
          小朋友们的专属AI教师<br>与学习伙伴
        </h1>
        <p class="mt-4 text-lg text-slate-600">一站式聚合全球顶尖AI大模型，为教学与科研注入无限动力。</p>
      </header>

      <!-- 专家团队网格 -->
      <main class="my-12">
        <h2 class="text-xl font-semibold text-slate-800 mb-6">认识你的AI专家团队</h2>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
          <div 
            v-for="expert in experts" 
            :key="expert.title"
            class="bg-white p-4 rounded-lg border border-slate-200 flex items-center gap-4 transition-all hover:border-primary hover:scale-105 duration-300"
          >
            <div 
              class="flex-shrink-0 w-12 h-12 flex items-center justify-center rounded-lg text-white text-2xl"
              :style="{ backgroundColor: expert.color }"
            >
              <i :class="expert.icon"></i>
            </div>
            <div>
              <h4 class="font-semibold text-slate-800">{{ expert.title }}</h4>
              <p class="text-slate-500 text-sm">{{ expert.description }}</p>
            </div>
          </div>
        </div>
      </main>

      <!-- 魔法时刻 (推至底部) -->
      <footer class="mt-auto">
        <h3 class="text-sm font-medium text-slate-500 mb-3">能力演示：</h3>
        <div class="w-full text-sm">
          <div class="p-3 mb-2 max-w-[90%] rounded-lg rounded-bl-none bg-white border border-slate-200">
            <span class="typewriter-cursor">{{ currentScenario.userQuery }}</span>
          </div>
          <div class="p-3 max-w-[90%] rounded-lg rounded-br-none bg-primary text-white ml-auto">
            <span class="typewriter-cursor">{{ currentScenario.aiResponse }}</span>
          </div>
        </div>
      </footer>
    </div>

    <!-- ==================== 右侧登录操作区 ==================== -->
    <div class="bg-white flex items-center justify-center p-8">
      <div class="w-full max-w-sm">
        <h2 class="text-3xl font-bold text-slate-800 mb-2">欢迎回来</h2>
        <p class="text-slate-500 mb-8">登录以继续探索AI的无限可能。</p>
        
        <form @submit.prevent="handleLogin">
          <div class="mb-4">
            <label for="username" class="block text-slate-700 font-medium mb-2">用户名</label>
            <input 
              type="text" 
              id="username" 
              v-model="loginForm.username"
              placeholder="请输入您的用户名或邮箱" 
              class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 transition"
            >
          </div>
          <div class="mb-6">
            <label for="password" class="block text-slate-700 font-medium mb-2">密码</label>
            <input 
              type="password" 
              id="password" 
              v-model="loginForm.password"
              placeholder="请输入您的密码" 
              class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 transition"
            >
          </div>
          <div class="flex items-center justify-between text-sm mb-8">
            <div class="flex items-center">
              <input 
                type="checkbox" 
                id="remember" 
                v-model="loginForm.remember"
                class="h-4 w-4 text-primary focus:ring-primary border-slate-300 rounded"
              >
              <label for="remember" class="ml-2 text-slate-600">记住我</label>
            </div>
            <a href="#" class="font-medium text-primary hover:text-primary-dark">忘记密码?</a>
          </div>
          <button 
            type="submit" 
            :disabled="isLoading"
            class="w-full py-3 px-4 bg-primary text-white font-bold rounded-lg hover:bg-primary-dark transform hover:-translate-y-0.5 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none"
          >
            {{ isLoading ? '登录中...' : '立即登录' }}
          </button>
        </form>
        
        <p class="text-center text-sm text-slate-600 mt-8">
          还没有账户? <a href="#" class="font-medium text-primary hover:text-primary-dark">立即注册</a>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const loginForm = ref({
  username: '',
  password: '',
  remember: false
})

const isLoading = ref(false)

// AI专家团队数据
const experts = ref([
  { 
    icon: 'fa-solid fa-graduation-cap', 
    color: '#6366F1', 
    title: 'Gemini 2.5 Pro (博学的大学教授)', 
    description: '知识渊博，逻辑严密。适合深度学术探讨、复杂问题推理。' 
  },
  { 
    icon: 'fa-solid fa-bolt', 
    color: '#3B82F6', 
    title: 'GPT-4o (全能的常春藤导师)', 
    description: '反应迅捷，善于沟通。精通多模态对话，是你的全能日常助手。' 
  },
  { 
    icon: 'fa-solid fa-feather-pointed', 
    color: '#EC4899', 
    title: 'Claude 3 Opus (富有创造力的文学家)', 
    description: '文笔优美，思想深刻。擅长长文写作、创意构思和伦理分析。' 
  },
  { 
    icon: 'fa-solid fa-microchip', 
    color: '#10B981', 
    title: 'DeepSeek-V3 (严谨的科研学者)', 
    description: '代码与逻辑大师。专注于编程、数学和需要精确推理的任务。' 
  }
])

// 魔法时刻演示数据
const scenarios = ref([
  { 
    userQuery: '请帮我将这句话翻译成更学术的英文："这个研究很重要"。', 
    aiResponse: 'Certainly. A more academic phrasing would be: "This research holds considerable significance within the field."' 
  },
  { 
    userQuery: '帮我设计一个关于"光合作用"的课堂互动问题。', 
    aiResponse: '好的，可以试试这个：如果植物进行光合作用需要二氧化碳，为什么我们还要种树来减少二氧化碳呢？' 
  },
  { 
    userQuery: '这段Python代码为什么会报错: `for i in range(len(list)-1)`?', 
    aiResponse: '这个错误很常见！`list` 是Python的关键字，不能用作变量名。另外，遍历列表时有更简洁的 `for item in my_list:` 写法。' 
  },
  { 
    userQuery: 'How can I order a coffee in English?', 
    aiResponse: 'You can say: "Hi, could I get a large latte, please?" They might ask "For here or to go?"' 
  }
])

const currentScenario = ref(scenarios.value[0])
let scenarioInterval: NodeJS.Timeout | null = null

// 打字机效果函数
const typeWriter = (element: HTMLElement, text: string, callback?: () => void) => {
  let i = 0
  element.innerHTML = ''
  const speed = 40
  
  const type = () => {
    if (i < text.length) {
      element.innerHTML += text.charAt(i)
      i++
      setTimeout(type, speed)
    } else if (callback) {
      callback()
    }
  }
  
  type()
}

// 更新魔法时刻的对话内容
const updateMagicMoment = (index: number) => {
  const scenario = scenarios.value[index]
  const userQueryEl = document.getElementById('user-query') as HTMLElement
  const aiResponseEl = document.getElementById('ai-response') as HTMLElement
  
  if (userQueryEl && aiResponseEl) {
    typeWriter(userQueryEl, scenario.userQuery, () => {
      setTimeout(() => typeWriter(aiResponseEl, scenario.aiResponse), 300)
    })
  }
}

// 登录处理
const handleLogin = async () => {
  const { username, password } = loginForm.value
  
  // 特殊登录：admin + 123456 直接跳转到首页
  if (username === 'admin' && password === '123456') {
    isLoading.value = true
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      ElMessage.success('登录成功！')
      router.push('/')
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败，请重试')
    } finally {
      isLoading.value = false
    }
    return
  }
  
  // 常规登录验证
  if (!username.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }
  
  if (!password.trim()) {
    ElMessage.warning('请输入密码')
    return
  }
  
  isLoading.value = true
  
  try {
    // 这里可以调用实际的登录API
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('登录成功！')
    router.push('/')
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 组件挂载和卸载
onMounted(() => {
  // 初始化魔法时刻演示
  updateMagicMoment(0)
  
  // 设置定时器轮播演示
  scenarioInterval = setInterval(() => {
    const currentIndex = scenarios.value.findIndex(s => s === currentScenario.value)
    const nextIndex = (currentIndex + 1) % scenarios.value.length
    currentScenario.value = scenarios.value[nextIndex]
    updateMagicMoment(nextIndex)
  }, 7000)
})

onUnmounted(() => {
  if (scenarioInterval) {
    clearInterval(scenarioInterval)
  }
})
</script>

<style scoped>
/* 打字机光标动画 */
.typewriter-cursor::after {
  content: '▋';
  animation: blink 0.7s infinite;
}

@keyframes blink {
  50% { opacity: 0; }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .grid-cols-2 {
    grid-template-columns: 1fr;
  }
}
</style>
